import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/lang.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/community_business/publish_page/publish_page.dart';
import 'package:xvideos/hj_page/community_business/publish_page/widget/publish_widget.dart';
import 'package:xvideos/hj_page/mine_business/widgets/common_alert.dart';
import 'package:xvideos/tools_base/file_upload/file_upload_tool.dart';
import 'package:xvideos/tools_base/loading/loading_alert_widget.dart';
import 'package:xvideos/hj_utils/api_service/vid_service.dart';
import 'package:xvideos/hj_utils/file_util.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/video_utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

class UploadVideoModel {
  String? localPath;
  String? localCover;
  String? remotePath;
  String? remoteCover;
  String? customCover;
  double? ratio;
  String? name;
  String? md5;
  int? playTime;
  int? size;
  String? sourceid;
  String? resolution;

  UploadVideoModel(
      {this.localPath,
      this.localCover,
      this.remotePath,
      this.remoteCover,
      this.ratio,
      this.name,
      this.playTime,
      this.size,
      this.sourceid,
      this.resolution,
      this.md5,
      this.customCover});

  copy() {
    return UploadVideoModel(
        localCover: localCover,
        localPath: localPath,
        remotePath: remotePath,
        remoteCover: remoteCover,
        resolution: resolution,
        ratio: ratio,
        name: name,
        playTime: playTime,
        size: size,
        sourceid: sourceid,
        md5: md5,
        customCover: customCover);
  }
}

class PublishController extends GetxController {
  // Rx<TagsBean?> topic = Rx(null);
  RxList<TagsBean> topics = <TagsBean>[].obs;

  Rx<String?> gold = Rx(null);

  RxList<String> imgs = [''].obs;

  final describeController = TextEditingController();

  final titleController = TextEditingController();
  final titleFouceN = FocusNode();
  final contentFouceN = FocusNode();
  final goldFouceN = FocusNode();

  // 链接的视频
  Rx<UploadVideoModel> video = Rx(UploadVideoModel());

  late PublishType type;

  @override
  void onInit() {
    super.onInit();

    type = Get.arguments ?? PublishType.homeImgText;
  }

  @override
  void onReady() {
    super.onReady();
  }

  topicNavigato(BuildContext context, LinkType type) {}

  /// 视频封面相关
  choseCover() async {
    final listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: Colors.white),
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: false,
    );
    if (listMedia.isEmpty) return;
    video.value = video.value.copy()..customCover = listMedia.first.path ?? '';
  }

  deleteCover() {
    video.value = video.value.copy()..customCover = null;
  }

  ///视频相关
  choseVideo() async {
    var pickedFile = await ImagePicker().pickVideo(source: ImageSource.gallery);
    if (pickedFile == null) return null;

    if (!File(pickedFile.path).existsSync()) {
      showToast("用户视频文件损坏或格式错误");
      return;
    }
    var path = pickedFile.path;
    if (path.toLowerCase().contains('weixin') || path.toLowerCase().contains('qq')) {
      showToast(Lang.REQUIRE_NOT_WEI_XIN_QQ);
      return;
    }

    final mediaInfo = await _checkVideoRule(path);
    if (mediaInfo == null) return;
    final coverPath_ = await VideoThumbnail.thumbnailFile(
      video: path,
      thumbnailPath: (await getTemporaryDirectory()).path,
      imageFormat: ImageFormat.PNG,
      quality: 100,
    );

    final videoM_ = UploadVideoModel(
        localCover: coverPath_,
        localPath: path,
        ratio: mediaInfo.ratio ?? 1,
        name: "${DateTime.now().toIso8601String()}.mp4",
        playTime: mediaInfo.playTime,
        size: mediaInfo.size,
        resolution: mediaInfo.resolution);

    video.value = videoM_..customCover = video.value.customCover;
  }

  deleteSelectVideo() {
    video.value = UploadVideoModel()..customCover = video.value.customCover;
  }

  /// 图集相关
  choseImg() async {
    final listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: Colors.white),
      galleryMode: GalleryMode.image,
      selectCount: 9 - (imgs.length - 1),
      showCamera: false,
    );
    if (listMedia.isEmpty) return;
    final ret = listMedia.map((e) => e.path ?? '').toList();
    imgs.insertAll(0, ret);
  }

  publish() async {
    final res = _checkEnable();
    if (res) {
      FocusManager.instance.primaryFocus?.unfocus();
      //上传图片前 先移除第一个占位
      List<String> imgs_ = [];

      if (type != PublishType.squireVideo) {
        imgs_.addAll(imgs);
        imgs_.remove('');
      }

      // 上传图片

      LoadingAlertWidget.show(Get.context!, title: "正在上传图片...");
      var picUrlList = await FileUpLoadTool().uploadImageList(imgs_, proCallback: (tIndex, tAll, proCount, totalCount) {
        LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
      });
      if (picUrlList?.isEmpty ?? true) {
        LoadingAlertWidget.cancel(Get.context!);
        showToast("图片上传失败");
        // imgs.insert(0, '');
        return;
      }
      LoadingAlertWidget.cancel(Get.context!);
      // List<String>? seriesCover;
      // if (type == Publishype.imageText || type == Publishype.video) {
      final seriesCover = picUrlList?.map((e) => e.coverImg ?? '').toList() ?? [];
      // }

      MediaInfo? mediaInfo;
      // 上传视频相关
      if (video.value.localPath != null) {
        LoadingAlertWidget.show(Get.context!, title: "正在上传视频...");
        mediaInfo = await VideoUtils.getMediaInfo(video.value.localPath ?? "");

        video.value.remoteCover = seriesCover.first;
        // final cover = await FileUpLoadTool().uploadImage(video.value.customCover ?? video.value.localCover ?? '',
        //     callback: (count, tAll) {
        //   LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (count / tAll)).toStringAsFixed(1)}%");
        // });

        if (video.value.remoteCover != null) {
          final fileR = await FileUpLoadTool().uploadFile(video.value.localPath ?? '', proCallback: (tIndex, tAll, proCount, totalCount) {
            LoadingAlertWidget.showExchangeTitle("正在上传视频${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
          });
          if (fileR != null) {
            video.value.remotePath = fileR.videoUri;
            video.value.md5 = fileR.md5;
            video.value.sourceid = fileR.id;
          } else {
            LoadingAlertWidget.cancel(Get.context!);
            showToast("视频上传失败");
          }
        } else {
          LoadingAlertWidget.cancel(Get.context!);
          showToast("视频封面上传失败");
        }
        LoadingAlertWidget.cancel(Get.context!);
      }

      final result = await VidService.submitVideo(
        title: titleController.text,
        newsType: _generateNewsType(),
        tags: topics.map((element) => element.id ?? '').toList(),
        seriesCover: seriesCover,
        coins: int.parse(gold.value ?? '0'),
        playTime: mediaInfo != null ? mediaInfo.playTime : null,
        mimeType: mediaInfo != null ? "mp4" : null,
        content: describeController.text,
        sourceID: video.value.sourceid,
        md5: video.value.md5,
        ratio: video.value.ratio,
        size: video.value.size,
        resolution: video.value.resolution,
        sourceURL: video.value.remotePath,
        cover: video.value.remoteCover,
      );

      if (result) {
        await Get.dialog(
          CommonAlert(
            title: "发布成功",
            desc: '帖子发布后将在24小时内进行审核，您可在【我的】-【我的帖子】中进行查看',
            rightBtn: '确定',
            showLeftButton: false,
          ),
        );
        Get.back();
      } else {
        showToast('发布失败');
      }
    }
  }

  /// 检查本地视频
  Future<MediaInfo?> _checkVideoRule(String path) async {
    if (path.isEmpty) {
      showToast("视频地址错误");
      return null;
    }

    MediaInfo? videoInfo = await VideoUtils.getMediaInfo(path);
    if (videoInfo == null) {
      showToast(Lang.VIDEO_GET_RESOURCE_FAIL);
      return null;
    }

    //时间
    if ((videoInfo.playTime ?? 0) < 30 && (videoInfo.playTime ?? 0) > 0) {
      showToast(Lang.VIDEO_DURATION_LESS_4S);
      return null;
    }

    //大小
    int sizeM = (videoInfo.size ?? 0) ~/ (MB_SIZE);
    if (sizeM > 300 || sizeM == 0) {
      showToast(Lang.VIDEO_SIZE_LESS_250M);
      return null;
    }

    //分辨率
    String resolution = videoInfo.resolution ?? '';
    if (resolution.isEmpty || !resolution.contains("*")) {
      showToast(Lang.VIDEO_GET_RESOURCE_FAIL);
      return null;
    }

    List<String> list = resolution.split("*");
    var curResolution = double.parse(list[0]) * double.parse(list[1]);
    if (curResolution < 360 * 360) {
      showToast(Lang.VIDEO_RESOLUTION_THEN_360);
      return null;
    }
    return videoInfo;
  }

  bool _checkEnable() {
    if (type == PublishType.homeImgText || type == PublishType.homeImg) {
      if (titleController.text.isEmpty) {
        showToast('请输入标题!');
        return false;
      }

      if (describeController.text.isEmpty && type == PublishType.homeImgText) {
        showToast('请输入描述!');
        return false;
      }
      if (imgs.length <= 2) {
        showToast('至少选择两张图片～');
        return false;
      }
      if (topics.isEmpty) {
        showToast('请选择话题哦～');
        return false;
      }
      return true;
    }
    if (type == PublishType.homeVideo) {
      if (titleController.text.isEmpty) {
        showToast('请输入标题!');
        return false;
      }
      if (describeController.text.isEmpty) {
        showToast('请输入描述!');
        return false;
      }
      if (video.value.localPath == null) {
        showToast('请选择需要上传的视频!');
        return false;
      }
      if (imgs.length <= 1) {
        showToast('请选择图片!');
        return false;
      }

      if (topics.isEmpty) {
        showToast('请选择话题哦～');
        return false;
      }
      return true;
    }
    if (type == PublishType.squireImgText) {
      if (topics.isEmpty) {
        showToast('至少选择一个话题哦～');
        return false;
      }
      if (describeController.text.isEmpty) {
        showToast('请输入描述!');
        return false;
      }

      if (imgs.length == 1) {
        showToast('请选择图片!');
        return false;
      }
      return true;
    }

    if (topics.isEmpty) {
      showToast('至少选择一个话题哦～');
      return false;
    }
    if (describeController.text.isEmpty) {
      showToast('请输入描述!');
      return false;
    }
    if (video.value.localPath == null) {
      showToast('请选择需要上传的视频!');
      return false;
    }

    return true;
  }

  String _generateNewsType() {
    if (type == PublishType.homeImg || type == PublishType.homeImgText || type == PublishType.squireImgText) return 'COVER';
    final duration = video.value.playTime ?? 0;
    if (duration <= 300) return 'SP';
    return 'SP';
  }
}
